﻿function getstyle() {
    if ($.cookie('current-skin'))
        return $.cookie('current-skin').replace('/assets/css/skins/', '').replace('.min.css', '');
    return null;
}
(function ($) {


    function getcol(des) {
        var cols = '';
        var f = 0;
        while (des.indexOf("$") >= 0) {
            if (f == 0) {
                ++f;
                des = des.substring(des.indexOf("$") + 1);
            }
            else {
                cols += des.substring(0, des.indexOf("$")) + ',';
                des = des.substring(des.indexOf("$") + 1);
                f = 0;
            }
        }
        return cols;

    }

    var SearchType = {simple: 0, advanced: 1}


    $.fn.table = function (parm) {
        if (parm.IsInit) {
            return;
        }
        parm.IsInit = true;


        var currentColor = getCurrentColor();
        var option = {
            //同步异步
            'async': true,
            //高级搜索查询对话框
            'advancedsearch': undefined,
            //actioncode
            'url': '',
            //排序
            'SortBy': '',
            //排序方式
            'SortOrder': '',
            //是否显示checkbox
            'check': true,
            //显示分页，默认true
            'ispage': true,
            //数据源，用于同步时赋值（用data赋值方式不支持分页）
            'data': undefined,
            //显示序号 ，默认true
            'no': true,
            //固定查询参数，无论是简单搜索还是高级搜索，都会将参数传到后端
            'stableparm': undefined,
            //简单查询参数
            'keys': [],
            //查询参数
            'parm': undefined,
            //是否显示search文本框
            'search': true,
            //查询文本框的placeholder
            'placeholder': '查询',
            //toolbar按钮
            'tools': [],
            //每页显示条数
            'pageSize': 15,
            //行按钮事件
            'events': [],
            //加载后执行
            'callback': undefined
        };
        this.culture = culture.getCulture();
        var searchType = SearchType.simple;
        var startIndex = 1;
        var mypage;
        var pagecontainer;
        var $this = $(this);

        this.$this = $this;
        var parent, event;
        var pageSize;

        var me = this;
        parm.ext = me;

        var tbody = $this.find('tbody');
        //模板行
        var templatetr = $(tbody.find('tr')[0]);
        var templatetd = templatetr.find('td');


        var loading;

        me.selectItems = function () {

            var selectedData = [];
            tbody.find('input:checkbox:checked').each(function () {
                var tablerow = $(this).parent("tr");
                selectedData.push(option.data[row.rowIndex]);
            });
        }

        me.reset = function (parm) {
            for (i in option) {
                if (parm[i] != undefined && parm[i] != null) {
                    option[i] = parm[i];
                }
            }
            if (!option.stableparm) option.stableparm = {};

            if (parm.placeholder && me.searchInput) {
                me.searchInput.attr('placeholder', parm.placeholder);
            }
        }

        me.reset(parm);

        me.resettoolbar = function () {

            tools();
        }


        //初始化容器
        function tools() {
            if (event)
                event.remove();

            function generateTool(event, tool) {
                var btn = $("<a  class='btn btn-default' style='font-size:14px;' ><i style='padding-right:3px; '></i><span></span></a>");
                var img = $("i", btn);
                if (tool.img) img.attr('class', tool.img); else img.remove();

                var text = tool.text;
                for (i in tool) {
                    if (i == 'data-culture') {
                        if (cultureData[tool[i]] && cultureData[tool[i]][me.culture]) {
                            text = cultureData[tool['data-culture']][me.culture];
                            break;
                        }
                    }

                }


                btn.find('span').html(text);
                btn.attr('title', text);
                var ishidden = false;
                if (tool.hidden) {
                    if (typeof (tool.hidden) == "function") {
                        ishidden = tool.hidden();
                    }
                    else ishidden = true;
                }
                if (!ishidden) {
                    if (tool.props) {
                        $.each(tool.props, function (dd, prop) {
                            for (i in prop) {
                                btn.attr(i, prop[i]);
                            }
                        })
                    }


                    if (tool.event instanceof Array) {
                        $.each(tool.event, function (ss, eve) {
                            for (i in eve) {
                                btn.on(i, function () {
                                    eve[i](me.selectItems(), parm)
                                });
                            }
                        })

                    } else
                        btn.click(function () {
                            tool.event(me.selectItems(), parm);
                        })


                    event.append(btn);
                }
            }


            if (option.tools && option.tools.length > 0) {
                event = $("<div class='DTTT btn-group'>");
                if (!option.search) {
                    me. $this.css('margin-top', '42px');
                    event.css('top', '-42px');
                }
                if (!option.ispage)
                    event.css('right', '0px');

                for (var ix = 0; ix < option.tools.length; ix++) {
                    generateTool(event, option.tools[ix]);
                }

                //for (i = option.tools.length - 1; i >= 0; i--) {
                //    generateTool(event, option.tools[i]);
                //}


                parent.append(event);
            }
        }


        (function (table) {
            //table.attr('class', 'table table-striped table-bordered table-hover dataTable no-footer ');

            table.attr("class", "table table-bordered table-striped table-condensed flip-content");
            var div_container = table.parent();
            //div_container.css({ 'padding': '2px 10px 10px 10px' })
            parent = $("<div class='dataTables_wrapper form-inline'>");

            //搜索

            if (option.search) {
                var textSearch = me.culture == "zh-CN" ? "搜索" : "Search";
                var textadvanceSearch = me.culture == "zh-CN" ? "高级搜索" : "Advance Search";

                style = 'margin-top:3px; margin-right:2px;'
                var search = option.advancedsearch ? $("<div class='dataTables_filter'><label ><input class='form-control input-sm' aria-controls='searchable' type='text' style='height:34px;' placeholder='" + (option.placeholder ? option.placeholder : textSearch) + "'></label>\
                    <a  class='btn btn-primary' style='margin:0 2px;'><i class='fa fa-search'></i>" + textSearch + "</a><a class=' btn btn-primary'  style='margin:0;'><i class='fa fa-search'></i>" + textadvanceSearch + "</a></div>")
                    : $("<div class='dataTables_filter'><label ><input class='form-control input-sm' aria-controls='searchable'  type='text' style='height:34px;' placeholder='" + (option.placeholder ? option.placeholder : textSearch) + "'></label>\
                       <a  class='btn btn-primary'  style='margin:0 2px;'><i class='fa fa-search'></i>" + textSearch + "</a></div>");
                var a_button = search.find('a');
                var input = search.find('input');
                me.searchInput = $(input[0]);
                if (option.advancedsearch)
                    $(".widget-buttons", option.advancedsearch).find('a').each(function () {
                        var a = $(this);
                        if (a.data('type') == 'reset') {
                            var btn = $("<input>").css('display', 'none').attr('type', 'reset');
                            option.advancedsearch.find('form').append(btn);
                            a.click(function () {
                                btn.click();
                            })

                        }
                    })
                function simplesearch(value) {
                    searchType = SearchType.simple;
                    if (option.keys) {
                        var keys = option.keys;
                        var tmp = {};
                        if (keys instanceof Array) {

                            if (keys && keys.length > 0) {
                                me.getdata(0, pageSize, function () {
                                    var tmp = {};
                                    if (keys && keys.length > 0)
                                        $.each(keys, function (i, val) {
                                            tmp[val] = value;
                                        })
                                    return tmp;
                                });
                            }
                        }
                        else if (typeof (keys) == "function") {
                            me.getdata(0, pageSize, keys(value));
                        }

                    }
                }

                $(input[0]).keydown(function (e) {
                    if (e.keyCode == 13) {
                        simplesearch($(input[0]).val());
                    }
                });
                $(a_button[0]).click(function () {
                    simplesearch($(input[0]).val());
                })
                if (option.advancedsearch) {
                    var searchBtn = $(".btn-primary", option.advancedsearch);
                    if (searchBtn && searchBtn.length > 0) {
                    }
                    else {
                        searchBtn = $(".btn-success", option.advancedsearch);
                    }

                    searchBtn.on('advanced', function () {
                        searchType = SearchType.advanced;
                    });
                    $(a_button[1]).click(function () {
                        option.advancedsearch.modal();
                    });
                }
            }

            //按钮
            tools();
            //
            if (option.ispage) {
                //var cookie = $.cookie("page-num");
                var cookie = $.cookie("page-num");
                var pagesize = $("<div class='dataTables_length' id='searchable_length'><label><select name='searchable_length' class='form-control input-sm' style='height:34px;' aria-controls='searchable'><option value='5'>5</option><option value='10'>10</option><option value='15'  selected='selected'>15</option><option value='20'>20</option><option value='50'>50</option></select></label></div>");
                parent.append(pagesize);
                var select = pagesize.find('select');
                if (cookie) {
                    select.val(parseInt(cookie));
                }
                select.change(function () {
                    pageSize = select.val();
                    me.getdata(0, select.val(), option.parm);
                    $.cookie("page-num", select.val(), {expires: 10});
                });
                pageSize = select.val();
            }

            table.remove();
            div_container.append(parent.append(search).append(table));
            if (option.ispage) {
                pagecontainer = $("<div class='row DTTTFooter'></div>");
                parent.append(pagecontainer)
            }
        })($this);
        var rel = getstyle();

        rel = rel ? 'bordered-' + rel : 'bordered-darkorange';

        me.sort = {
            SortBy: option.SortBy ? option.SortBy : '',
            SortOrder: option.SortOrder ? option.SortOrder : ''
        };

        //title的第一列
        $($this.find('thead')).attr('class', rel);


        var trs = $this.find('thead tr'), tr = trs.eq(trs.length - 1);

        var title = tr.children().eq(0);
        //var title = $this.find('thead tr td').length == 0 ? $this.find('thead tr th') : $this.find('thead tr td');

        var flag = 0;


        //选择
        if (option.check) {
            ++flag;
            me.selectall = $("<th class='check'><input type='checkbox'  ></th>");
            $(title[0]).before(me.selectall);
            $(templatetd[0]).before($("<td class='check'><input type='checkbox'   ></td>"));
            $(me.selectall.find('input')).on('click', function () {

                tbody.find('input:checkbox').prop("checked", this.checked);
                //$this.find('input:checkbox').attr('checked', this.checked);
            })
        }
        //序号
        if (option.no) {
            ++flag;
            $(title[0]).before($("<th style='text-align:center;width: 80px;' class='no'><div style='min-width:40px;max-width: 80px;'>" + (me.culture == 'zh-CN' ? "序号" : 'No.') + "</div></th>"));
            $(templatetd[0]).before($("<td  style='text-align:center' class='no'>$no$</td>"));

        }


        trs.each(function (index) {
            var $this = $(this);
            if ($this.children().length == 1 && index != trs.length - 1)
                $this.children().attr("colspan", trs.eq(trs.length - 1).children().length).css("text-align", "center");
        });

        templatetd = templatetr.find('td');

        templatetr.remove();
        templatetr.removeClass("row-no-display");

        //loading = $("<tr><td class='loading' colspan='" + templatetd.length + "'></td></tr>");

        var cols = []
        $.each(templatetd, function (i, val) {

            cols.push(getcol($(val).html()));
        })

        var sorts = $this.find('.sorting');


        sorts.each(function () {
            try {
                //获得绑定的列名
                var sort = {};
                sort.SortBy = cols[this.cellIndex].split(',')[0];
                if (me.sort.SortBy.toUpperCase().trim() == sort.SortBy.toUpperCase().trim() && (me.sort.SortOrder.toLowerCase().trim() == 'asc' || me.sort.SortOrder.toLowerCase().trim() == 'desc')) {
                    sort.SortOrder = me.sort.SortOrder.toLowerCase().trim();
                    $(this).attr('class', 'sorting_' + sort.SortOrder);
                }
                else {
                    sort.SortOrder = 'desc';
                }

                $(this).click(function () {
                    sorts.attr('class', 'sorting');
                    sort.SortOrder == 'desc' ? (sort.SortOrder = 'asc', $(this).attr('class', 'sorting_asc')) : (sort.SortOrder = 'desc', $(this).attr('class', 'sorting_desc'));

                    me.sort = sort;
                    me.getdata(0, pageSize);
                });
            } catch (e) {

            }

        })


        me.refresh = function () {
            if (me.selectall) {
                me.selectall.prop("checked", false);
            }

            if (!option.async) {
                option.data = parm.data;
                tbody.empty();
                binddata();
            } else
                me.getdata(0, pageSize);
        }

        if (option.searchbtn) {
            option.searchbtn.click(function () {
                me.refresh();
            })
        }

        function generateparm(pageIndex, pageSize, handler) {
            var parm = {};
            if (option.stableparm) {
                var stableparm;
                if (typeof (option.stableparm) == "function") {
                    stableparm = option.stableparm();
                }

                else stableparm = option.stableparm;
                for (i in stableparm)
                    parm[i] = stableparm[i];
            }
            if (searchType == SearchType.simple) {
                if (option.keys) {
                    var keys = option.keys;

                    if (keys instanceof Array) {
                        if (keys && keys.length > 0) {
                            $.each(keys, function (i, val) {
                                parm[val] = me.searchInput.val();
                            })
                        }
                    }
                    else if (typeof (keys) == "function") {
                        var tmp = keys(me.searchInput.val());
                        if (tmp.QueryItems)
                            parm.QueryItems = tmp.QueryItems;

                    }

                }

            }
            else {
                if (option.parm) {
                    var tmp = option.parm(option.dialog);
                    if (tmp.QueryItems)
                        parm.QueryItems = tmp.QueryItems;
                    else
                        for (i in tmp)
                            parm[i] = tmp[i];
                }
            }
            if (option.ispage) {
                parm.page = {
                    SortBy: me.sort.SortBy,
                    SortOrder: me.sort.SortOrder,
                    pageIndex: pageIndex,
                    pageSize: pageSize,
                    token: context.token
                }
            }
            parm.searchType = searchType;
            return parm;
        }

        me.generateparm = generateparm;
        me.getdata = function (pageIndex, pageSize, handler) {
            startIndex = option.ispage ? pageIndex * pageSize + 1 : 1;
            tbody.empty();
            //tbody.append(loading);
            var url;
            if (option.url instanceof Array) {
                if (option.url.length > 1)
                    url = option.url[searchType];
            }
            else if ((typeof option.url == 'string') && option.url.constructor == String) {
                if (option.url.indexOf(',') > 0) {
                    var urlarray = option.url.split(',');
                    url = urlarray[searchType];
                }
                else url = option.url;
            }
            else url = option.url;

            $.request(url, generateparm(pageIndex, pageSize, handler), function (data) {
                //loading.remove();
                tbody.empty();
                if (option.ispage) {
                    if (mypage)
                        mypage.dispose();
                    mypage = new pager(pagecontainer, pageIndex, pageSize, data.totalCount);
                    option.data = data.list || data;
                    if (option.data && option.data.length > 0)
                        binddata();
                    else {
                        var empty = $("<tr><td style='text-align:center' colspan='" + templatetd.length + "'>无数据</td></tr>");
                        tbody.append(empty);
                        return;
                    }
                }
                else {
                    if (data && data instanceof Array)
                        option.data = data;
                    else if (data.list && data.list instanceof Array)
                        option.data = data.list;
                    else {
                        var empty = $("<tr><td  style='text-align:center'  colspan='" + templatetd.length + "'>无数据</td></tr>");
                        tbody.append(empty);
                        return;
                    }
                    ;
                    binddata();
                }

            })

        }


        if (option.data) {
            binddata();
        }
        else if (option.url) {

            me.getdata(0, pageSize);
        }
        else {
        }


        function binddata() {

            $.each(option.data, function (i, val) {
                var tmp = templatetr.clone();
                $this.append(tmp);
                var tds = $(tmp.find('td'));
                $.each(tds, function (k, v) {
                    var $v = $(v);
                    var source = $v.html();
                    try {
                        var col = cols[k].split(',');
                        if ($v.data('translate')) {
                            switch ($v.data('translate')) {
                                case 'yesorno':
                                    var colname = col[0];
                                    var colnames = col[0].split('|');
                                    var yes, no;
                                    me.culture == "zh-CN" ? (yes = "是", no = "否" ) : (yes = "Yes", no = "No" );
                                    if (colnames.length > 1) {
                                        colname = me.culture == "zh-CN" ? colnames[0] : colnames[1]
                                    }
                                    if (val[colname] == undefined || val[colname] == null)
                                        source = "";
                                    else {
                                        source = val[colname] == 1 ? yes : no;
                                    }
                                    break;
                            }
                        }
                        else if ($v.attr('render')) {
                            source = option.events[$v.attr('render')](val, $v);
                        }
                        else if (($v.attr('dateformat')||$v.data("dateFormat") )&& col.length > 0) {
                            source = source.replace('$' + col[0] + '$', moment(val[col[0]]).formatUTC($v.attr('dateformat')||$v.data("dateFormat")));
                        }
                        else
                            $.each(col, function (m, n) {
                                if (n) {
                                    if (n == 'no') {
                                        source = source.replace('$' + n + '$', (i + startIndex));
                                    } else {
                                        var colname = n;
                                        var colnames = n.split('|');

                                        if (colnames.length > 1) {
                                            colname = me.culture == "zh-CN" ? colnames[0] : colnames[1]
                                        }
                                        source = source.replace('$' + n + '$', (val[colname] == undefined || val[colname] == null) ? '' : val[colname]);
                                    }
                                }
                            })
                        $v.html(source);
                        var events = $v.find('a');
                        if (events) {
                            $.each(events, function (l, e) {
                                var $e = $(e);
                                var purview = false;
                                if ($e.data('purview')) {

                                    if (option.events[$e.data('purview')])
                                        purview = option.events[$e.data('purview')](val);
                                }
                                if (purview) {
                                    $e.remove();
                                }
                                else {
                                    var tmp = false;
                                    if ($e.data('type') == 'button') {
                                        tmp = true;
                                        $e.attr('class', 'btn-search-button');//.css('color', '#222');
                                    }
                                    //render
                                    if ($e.data('render') && option.events[$e.data('render')]) {
                                        option.events[$e.data('render')](val, parm, i, $e);
                                    }
                                    //if (tmp&&!$e.hasClass('disabled'))
                                    //    $e.css('background-color', currentColor).css('color', '#fff');;
                                    var rel = $e.attr('rel');

                                    if (rel) {
                                        if (rel.indexOf(':') >= 0) {
                                            var eve = eval("(" + rel + ")");
                                            for (e in eve) {
                                                $e.bind(e, function () {
                                                    option.events[eve[i]](val, parm, i);

                                                })
                                            }

                                        } else
                                            $e.click(function () {

                                                option.events[rel](val, parm, i);
                                            })
                                    }

                                    var render = $e.attr('render');
                                    if (render) {
                                        $e.html(option.events[render](val, parm, i,$e));
                                    }
                                }

                            });
                        }

                    } catch (e) {

                    }


                })
            });

            if (option.callback)
                option.callback(me.$this);
            return me;
        }


        function pager(container, pageIndex, pageSize, totalcount) {
            var totalpage = Math.ceil(totalcount / pageSize);

            var des = $("<div class='col-sm-6'><div class='dataTables_info'></div></div>");
            var div = des.find('div');
//The current first pages, a total of 0 pages; a total of 0 records
            div.html((me.culture == "zh-CN" ? "当前第" : "The current") + "<span style='color:red'>" + (pageIndex + 1) + "</span>" +
                (me.culture == "zh-CN" ? "页，共" : "pages, a total of") + "<span style='color:red'>" + totalpage + "</span>" +
                (me.culture == "zh-CN" ? "页;共计" : "pages; a total of") + "<span style='color:red'>" + totalcount + "</span>" + (me.culture == "zh-CN" ? "条记录" : "records"));
            container.append(des);
            var pagination = $("<div class='col-sm-6'><div class='dataTables_paginate paging_bootstrap'><ul class='pagination'></ul></div></div>");
            var ul = pagination.find('ul');
            container.append(pagination);

            var first = $(" <li class='j-first disabled'  title='第一页' ><a class='first' href='#'><span class='glyphicon glyphicon-fast-backward'></span></a></li>");
            var pre = $(" <li title='上一页' style='j-prev disabled'><a class='previous' href='#'><span  class='glyphicon glyphicon-step-backward'></span></a></li>");
            var jumpto = $("<li class='jumpto'><div class='form-group'><span class='input-icon icon-right'></span></div></li>")
            var input = $("<input class='textInput' type='text' class='form-control'value='" + (pageIndex + 1) + "' />");
            var goto = $("<i class='glyphicon glyphicon-ok maroon'></i>");
            jumpto.find('span').append(input).append(goto);

            var next = $(" <li title='下一页' class='j-next'><a  class='next' href='#'><span class='glyphicon glyphicon-step-forward'></span></a></li>");
            var end = $(" <li title='末页'  class='j-next'><a class='last' href='#'><span class='glyphicon glyphicon-fast-forward'></span></a></li>");
            var refresh = $(" <li title='刷新'  class='j-last'><a class='last' href='#'><span class='fa  fa-refresh'></span></a></li>");
            ul.append(first).append(pre).append(jumpto).append(next).append(end).append(refresh);


            input.keydown(function (e) {
                if (e.keyCode == 13) {
                    jump()
                }
            })

            goto.click(function () {
                jump();
            })
            function jump() {
                try {
                    var num = parseInt(input.val()) - 1;
                    if (num >= 0 && num < totalpage)
                        changepage(num);
                } catch (e) {
                    alert('请正确录入');
                    me.input.val(pageIndex + 1);
                }
            }

            function nextpage() {
                if (pageIndex < totalpage)
                    changepage(++pageIndex);
            }

            function prepage() {
                if (pageIndex > 0)
                    changepage(--pageIndex);
            }

            function changepage(pageNum) {
                if (pageNum == 0 || (pageNum > 0 && pageNum < totalpage)) {
                    me.getdata(pageNum, pageSize);
                }
            }

            if (pageIndex == 0) {
                first.attr('class', 'j-first disabled');
                pre.attr('class', 'j-first disabled');
            }
            else {
                first.attr('class', 'j-first');
                pre.attr('class', 'j-first');
                first.click(function () {
                    changepage(0);
                })
                pre.click(function () {
                    prepage();
                })
            }
            if (pageIndex >= totalpage - 1) {

                next.attr('class', 'j-next disabled');
                end.attr('class', 'j-end disabled');
            }
            else {
                next.attr('class', 'j-next');
                end.attr('class', 'j-end');
                next.click(function () {
                    nextpage();

                });
                end.click(function () {
                    changepage(totalpage - 1);
                })
            }

            refresh.click(function () {
                searchType = SearchType.simple;
                if (me.searchInput)
                    me.searchInput.val('');
                me.refresh();
            })

            pager.prototype.dispose = function () {
                container.html('');
                totalpage = null;
                panelBar = null;
                pagination = null;
                ul = null;
                first = null;
                pre = null;
                jumpto = null;
                next = null;
                end = null;


            }
            $("li ", ul).each(function () {
                var $this = $(this);
                if (!$this.hasClass('disabled'))
                    $("a", $this).css('color', currentColor);
            })
        }


        this.selectItems = function () {
            var selectdata = [];
            tbody.find('input:checkbox:checked').each(function () {
                selectdata.push(option.data[this.parentElement.parentElement.rowIndex - 1]);
            })
            return selectdata;
        }
    }
})(jQuery);

//$(function () {

//    $(".table").table({
//        url: "/sys/menu/pager",
//        check: true,
//        ispage: true,
//        pagecontainer: $(".panelBar"),
//        no: true,
//        events: {
//            delete: function (row) {
//                alert(row.menuName);
//            }
//        }
//    });
//})

